package com.kuaimacode.kframework.api.exception;

import com.alibaba.fastjson.JSON;
import com.kuaimacode.kframework.common.Constant;
import com.kuaimacode.kframework.exception.Error;
import com.kuaimacode.kframework.exception.ErrorEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author qinyong
 * @Title:
 * @Package com.kuaimacode.kframework.api.exception
 * @Description: created by IntelliJ IDEA
 * @date 2019-03-09 21:07
 */
@Slf4j
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class WebExceptionHandlerControllerAdvice implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        if (ex instanceof AccessDeniedException) {
            logError(request, ex);
            writeErrorAjax(response, ErrorEnum.DOS_NOT_HAVE_PERMISSION.getCode(), ErrorEnum.DOS_NOT_HAVE_PERMISSION.getMsg());
        }
        return null;
    }

    private void logError(HttpServletRequest request, Exception e) {
        log.error("[URI: " + request.getRequestURI() + "]", e);
    }

    private void writeErrorAjax(HttpServletResponse response, String code, String msg) {
        try {
            response.setCharacterEncoding(Constant.UTF8);
            PrintWriter out = response.getWriter();
            Error error = new Error();
            error.setCode(code);
            error.setMessage(msg);
            out.println(JSON.toJSONString(error));
            out.flush();
            out.close();
        } catch (Exception e) {
            log.error("write response when handle mvc exception error", e);
        }
    }
}
